package com.atguigu.spzx.manager.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.manager.listener.CategoryReadListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import com.atguigu.spzx.model.vo.product.CategoryExcelVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * Category 里 有个属性hasChildren  ,这是前端用于判断有没有下一级的,我们需要查询到该categorie对象有无子结点进行赋值
     * @param parentId
     * @return
     */
    @Override
    public List<Category> findByParentId(Long parentId) {
        List<Category> categoryList = categoryMapper.selectByParentId(parentId);
        for (Category category : categoryList) {
            //对每个category对象进行子结点判断
            Long childrenNum = categoryMapper.countChildrenById(category.getId());
            category.setHasChildren(false);
            if (childrenNum>0){
                category.setHasChildren(true);
            }
        }
        return categoryList;
    }

    @SneakyThrows
    @Override
    public void importData(MultipartFile multipartFile) {
        InputStream fileInputStream = multipartFile.getInputStream();
        //使用easyexcel的工具来逐行读取
        EasyExcel.read(fileInputStream,CategoryExcelVo.class,new CategoryReadListener(categoryMapper)).sheet("分类数据").doRead();

    }

    @SneakyThrows
    @Override
    public void exportData(HttpServletResponse response) {
        List<CategoryExcelVo> dataList=new ArrayList<>();
        List<Category> categoryList = categoryMapper.findAll();
        for (Category category : categoryList) {
            CategoryExcelVo vo=new CategoryExcelVo();
            vo.setId(category.getId());
            vo.setName(category.getName());
            vo.setParentId(category.getParentId());
            vo.setImageUrl(category.getImageUrl());
            vo.setStatus(category.getStatus());
            vo.setOrderNum(category.getOrderNum());
            dataList.add(vo);
        }
        EasyExcel.write(response.getOutputStream(),CategoryExcelVo.class).sheet("test").doWrite(dataList);
    }
}
